from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import UserProfile, Address


class UserLoginForm(forms.Form):
    """用户登录表单"""
    username = forms.CharField(
        label='用户名或邮箱',
        max_length=100,
        widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': '请输入用户名或邮箱'})
    )
    password = forms.CharField(
        label='密码',
        widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': '请输入密码'})
    )
    remember_me = forms.BooleanField(
        label='记住我',
        required=False,
        widget=forms.CheckboxInput(attrs={'class': 'form-check-input'})
    )


class UserRegisterForm(UserCreationForm):
    """用户注册表单"""
    email = forms.EmailField(
        label='邮箱',
        max_length=254,
        widget=forms.EmailInput(attrs={'class': 'form-control', 'placeholder': '请输入邮箱'})
    )
    
    class Meta:
        model = User
        fields = ('username', 'email', 'password1', 'password2')
        widgets = {
            'username': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '请输入用户名'}),
        }
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['password1'].widget.attrs.update({'class': 'form-control', 'placeholder': '请输入密码'})
        self.fields['password2'].widget.attrs.update({'class': 'form-control', 'placeholder': '请再次输入密码'})
    
    def clean_email(self):
        email = self.cleaned_data.get('email')
        if User.objects.filter(email=email).exists():
            raise forms.ValidationError('该邮箱已被注册')
        return email


class UserProfileForm(forms.ModelForm):
    """用户个人资料表单"""
    class Meta:
        model = UserProfile
        fields = ('avatar', 'gender', 'birthday', 'bio', 'phone')
        widgets = {
            'gender': forms.Select(attrs={'class': 'form-select'}),
            'birthday': forms.DateInput(attrs={'class': 'form-control', 'type': 'date'}),
            'bio': forms.Textarea(attrs={'class': 'form-control', 'rows': 3}),
            'phone': forms.TextInput(attrs={'class': 'form-control'}),
        }


class AddressForm(forms.ModelForm):
    """收货地址表单"""
    class Meta:
        model = Address
        exclude = ('user', 'created_time', 'updated_time')
        widgets = {
            'receiver': forms.TextInput(attrs={'class': 'form-control'}),
            'province': forms.Select(attrs={'class': 'form-select'}),
            'city': forms.Select(attrs={'class': 'form-select'}),
            'district': forms.Select(attrs={'class': 'form-select'}),
            'street': forms.Select(attrs={'class': 'form-select'}),
            'address': forms.TextInput(attrs={'class': 'form-control'}),
            'zip_code': forms.TextInput(attrs={'class': 'form-control'}),
            'phone': forms.TextInput(attrs={'class': 'form-control'}),
            'is_default': forms.CheckboxInput(attrs={'class': 'form-check-input'}),
        }


class PasswordChangeForm(forms.Form):
    """
    密码修改表单 - 用于用户修改密码
    包含当前密码、新密码和确认新密码字段
    """
    current_password = forms.CharField(
        label='当前密码',
        widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': '请输入当前密码'}),
        error_messages={'required': '请输入当前密码'}
    )
    new_password = forms.CharField(
        label='新密码',
        min_length=8,
        widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': '请输入新密码（至少8位）'}),
        error_messages={
            'required': '请输入新密码',
            'min_length': '密码长度不能少于8位'
        }
    )
    confirm_password = forms.CharField(
        label='确认新密码',
        widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': '请再次输入新密码'}),
        error_messages={'required': '请再次输入新密码'}
    )

    def clean_confirm_password(self):
        """验证两次输入的密码是否一致"""
        new_password = self.cleaned_data.get('new_password')
        confirm_password = self.cleaned_data.get('confirm_password')
        if new_password and confirm_password and new_password != confirm_password:
            raise forms.ValidationError('两次输入的密码不一致')
        return confirm_password


class ForgotPasswordForm(forms.Form):
    """
    忘记密码表单 - 用于用户申请重置密码
    包含邮箱字段
    """
    email = forms.EmailField(
        label='邮箱',
        widget=forms.EmailInput(attrs={'class': 'form-control', 'placeholder': '请输入您注册时使用的邮箱'}),
        error_messages={'required': '请输入邮箱', 'invalid': '请输入有效的邮箱地址'}
    )
    
    def clean_email(self):
        """验证邮箱是否存在"""
        email = self.cleaned_data.get('email')
        if not User.objects.filter(email=email).exists():
            raise forms.ValidationError('该邮箱未注册')
        return email


class VerifyCodeForm(forms.Form):
    """
    验证码表单 - 用于验证用户输入的验证码
    包含验证码字段
    """
    verification_code = forms.CharField(
        label='验证码',
        min_length=6,
        max_length=6,
        widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': '请输入6位验证码'}),
        error_messages={
            'required': '请输入验证码',
            'min_length': '验证码长度应为6位',
            'max_length': '验证码长度应为6位'
        }
    )
    email = forms.EmailField(widget=forms.HiddenInput())


class ResetPasswordForm(forms.Form):
    """
    重置密码表单 - 用于用户设置新密码
    包含新密码和确认新密码字段
    """
    new_password = forms.CharField(
        label='新密码',
        min_length=8,
        widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': '请输入新密码（至少8位）'}),
        error_messages={
            'required': '请输入新密码',
            'min_length': '密码长度不能少于8位'
        }
    )
    confirm_password = forms.CharField(
        label='确认新密码',
        widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': '请再次输入新密码'}),
        error_messages={'required': '请再次输入新密码'}
    )
    
    def clean_confirm_password(self):
        """验证两次输入的密码是否一致"""
        new_password = self.cleaned_data.get('new_password')
        confirm_password = self.cleaned_data.get('confirm_password')
        if new_password and confirm_password and new_password != confirm_password:
            raise forms.ValidationError('两次输入的密码不一致')
        return confirm_password